package com.atdel.demo14;


import java.util.concurrent.locks.ReentrantLock;

/**
 * @BelongsProject: java_study
 * @BelongsPackage: com.atdel.demo14
 * @Author: Del
 * @CreateTime: 2025-03-12  19:40
 * @Description: TODO
 * @Version: 1.0
 */
public class Printer {

     private  final ReentrantLock locks = new ReentrantLock();
    // 同步方法：使用 this 作为锁对象
    public synchronized void printWithSyncMethod(String user, String content) {
        System.out.println(user + ": " + content);
    }

    // 同步块：使用 this 作为锁对象
    public void printWithSyncBlock(String user, String content) {
        synchronized (this) {
            locks.lock();
            System.out.println(user + ": " + content);
        }
    }

    // 同步块：使用 Class 对象作为锁对象
    public void printWithClassLock(String user, String content) {
        synchronized (Printer.class) {
            System.out.println(user + ": " + content);
        }
    }

    // 同步块：使用自定义锁对象
    private final Object lock = new Object();
    public void printWithCustomLock(String user, String content) {
        synchronized (lock) {
            System.out.println(user + ": " + content);
        }
    }
}
